package com.free.bsf.eureka.client.limitrate;

import java.util.HashMap;
import java.util.regex.Pattern;

import com.free.bsf.core.util.ConvertUtils;
import com.free.bsf.core.util.StringUtils;

import lombok.Getter;
import lombok.Setter;
import lombok.val;

public class LimitRateConfig {
    @Getter @Setter
    String method;
    @Getter @Setter
    int period;
    @Getter @Setter
    String key;
    @Getter @Setter
    String provider;
    @Getter @Setter
    int max;

    private Pattern pattern;
    public static LimitRateConfig create(String config){
        val c = new LimitRateConfig();
        HashMap<String,String> kvs = new HashMap<>();
        for(val kvStr: config.split(";")){
            val kv = kvStr.split("=");
            kvs.put(kv[0],kv[1]);
        }
        c.method = kvs.get("method");
        c.period = ConvertUtils.tryConvert(kvs.get("period"),int.class);
        c.key = kvs.get("key");
        c.provider = kvs.get("provider");
        c.max = ConvertUtils.tryConvert(kvs.get("max"),int.class);
        if(StringUtils.isEmpty(c.method)){
            return null;
        }
        if(StringUtils.isEmpty(c.key)){
            c.key = "@@"+KeyExpression.class.getName()+"::example";
        }
        if(c.period>0){
            c.period = ConvertUtils.tryConvert(c.period,int.class);
        }else{
            c.period=1;
        }
        if(c.max>0){
            c.max = ConvertUtils.tryConvert(c.max,int.class);
        }else{
            c.max=1;
        }
        if(StringUtils.isEmpty(c.provider)){
            c.provider="local";
        }
        return c;
    }
    public boolean matchMethod(String method){
        if(pattern == null) {
            pattern = Pattern.compile(this.method);
        }
        return pattern.matcher(method).find();
    }

    private KeyExpression keyExpression;
    public String parseKey(String className,String methodName){
        if(keyExpression == null){
            keyExpression = new KeyExpression(key);
        }
        return keyExpression.parse(className,methodName);
    }
    
    public String toString() {
        StringBuilder sb=new StringBuilder();
        sb.append("{").append("key:").append(this.getKey()).append(",method:").append(this.getMethod()).append(",period:").append(this.getPeriod()).append(",provider:").append(this.getProvider()).append(",max:").append(this.getMax()).append("}");
        return sb.toString();
    }
}
